#!/bin/bash
function install_mysql() {
    echo -e "${blue}当前正在执行的操作为:${nocolor} ${green}安装MySQL${nocolor}"
    echo ""
    mysqlPid=`pidof mysqld`
    mysqlFile=`ls /var/lib/mysql/ 2>/dev/null`
    if [ -n "$mysqlPid" -o -n "$mysqlFile" ];then
        echo -ne "$Warn 检查到系统已经存在MySQL，继续则会删除之前的安装
继续[Yy,Enter],退出[Nn]: "
        read isYn
        [[ $isYn != [Nn] ]] || { sleep 0.5;return 1; }
        echo ""
    fi
    mysql_ins_type=
    mysql_ins_ver=
    mysql_charset=
    mysql_passwd=
    mysql_lower_case=
    echo -e "请选择安装方式?
1 离线安装
2 在线安装"
    while [[ $mysql_ins_type != [12] ]]
    do
        echo -ne "请选择[2]: "
        read mysql_ins_type
        mysql_ins_type=${mysql_ins_type:-2}
    done
    if [ "$mysql_ins_type" == "1" ];then
        mysql_insType="离线安装"
    else
        mysql_insType="在线安装"
    fi
    echo ""
    
    if [ "$die_network" == "true" -a "$mysql_ins_type" == "2" ];then
        echo -e "$Error 检测到你的系统并未联网，请使用离线方式安装MySQL！"
        anykeyback
        return 1
    fi
    
    echo -e "选择需要安装的MySQL版本?
1 MySQL 5.6
2 MySQL 5.7
3 MySQL 8.0"
    while [[ $mysql_ins_ver != [123] ]]
    do
        echo -ne "请选择[1]: "
        read mysql_ins_ver
        mysql_ins_ver=${mysql_ins_ver:-1}
    done
    echo ""

    echo -e "请选择MySQL使用的字符集?
1 UTF8
2 UTF8MB4
3 GBK"
    while [[ $mysql_charset != [123] ]]
    do
        echo -ne "请选择[2]: "
        read mysql_charset
        mysql_charset=${mysql_charset:-2}
    done
    echo ""

    echo -ne "设置MySQL用户ROOT密码
若密码为空或小于6位数为则使用随机密码
请输入密码: "
    read mysql_passwd
    echo ""
    
    echo -e "表名是否区分大小写?
1 区分
2 不区分"
    while [[ $mysql_lower_case != [12] ]]
    do
        echo -ne "请选择[1]: "
        read mysql_lower_case
        mysql_lower_case=${mysql_lower_case:-1}
    done
    echo ""
    
    if [ -z "$mysql_passwd" ] || [ ${#mysql_passwd} -lt 6 ];then
        random_pw=`strings /dev/urandom | grep -o '[[:alnum:]]' | head -n 4 | tr -d '\n'`
        mysql_passwd=MyPIo01_$random_pw
    else
        mysql_passwd=${mysql_passwd// /}
    fi
    
    if [ "$mysql_charset" == "1" ];then 
        mysql_char_set=utf8
    elif [ "$mysql_charset" == "2" ];then
        mysql_char_set=utf8mb4
    else
        mysql_char_set=gbk
    fi
    
    if [ "$mysql_lower_case" == "1" ];then
        mysql_lower_case=0
        mysql_lower_case_YN=Yes
    else
        mysql_lower_case=1
        mysql_lower_case_YN=No
    fi

    if [ "$mysql_ins_ver" == "1" ];then
        mysql_big_ver="MySQL5.6"
    elif [ "$mysql_ins_ver" == "2" ];then
        mysql_big_ver="MySQL5.7"
    else
        mysql_big_ver="MySQL8.0"
    fi
    
    echo -ne "${blue}MySQL 安装信息汇总${nocolor}
------------------------------------
MySQL版本：$mysql_big_ver
安装方式: $mysql_insType
MySQL字符集：$mysql_char_set
是否区分大小写：$mysql_lower_case_YN
MySQL密码：$mysql_passwd
------------------------------------
继续[Yn,Enter], 退出[Nn]: "
read isYn
[[ $isYn != [Nn] ]] || { sleep 0.5;return 1; }

    echo ""
    echo -e  "$Info ${purple}将会安装${mysql_big_ver}${nocolor}"
    echo -e "$Info ${purple}安装环境检测${nocolor}"
    
    if [ "$system_ver" == "8" ];then
        if [ "$mysql_ins_ver" == "1" -o "$mysql_ins_ver" == "2" ];then
          echo -e "$Error CentOS 8不支持使用RPM方式安装MySQL5.6及5.7版本！！！\n请使用源码编译方式手动安装！！！"
          return 1
        fi
    fi
    echo -e "$Info ${purple}清理之前的安装环境及rpm包${nocolor}"
    service mysql stop>/dev/null 2>&1 || service mysqld stop>/dev/null 2>&1
    killall mysqld>/dev/null 2>&1
    rpm -qa |grep -i mysql|xargs -t rpm -e --nodeps >/dev/null 2>&1
    rpm -qa |grep -i mariadb|xargs -t rpm -e --nodeps >/dev/null 2>&1
    if [ -d /var/lib/mysql ];then
      /bin/mv -f /var/lib/mysql /var/lib/mysql.bak$RANDOM>/dev/null
    fi
    mv -f /etc/my.cnf /etc/my.cnf.bak>/dev/null 2>&1
    mv -f /usr/my.cnf /usr/my.cnf.bak>/dev/null 2>&1
    rm -rf ~/.mysql_secret>/dev/null 2>&1

    if [ "$mysql_ins_type" == "1" ];then
        install_mysql_offline
    else
        install_mysql_online
    fi
    
    if [ -f /etc/my.cnf ];then
        my_conf=/etc/my.cnf
    elif [ -f /usr/my.cnf ];then
        my_conf=/usr/my.cnf
    else
        echo -e "$Error 未找到my.cnf文件，请确定MySQL-server软件包是否安装"
        anykeyback
        return 1
    fi
    
    echo -e "$Info ${purple}设置MySQL参数${nocolor}"
    
    attach_point=`cat $my_conf |grep -E "\[*\]$"|grep -v "#"|grep -v "\[mysqld\]"|head -n1`
    attach_point=${attach_point//\[/\\[}
    attach_point=${attach_point//\]/\\]}
    #如果有其他[]标签，则保存my.cnf自标签后面的配置参数
    if [ -z "$attach_point" ];then
        attach_point="none_attach_point"
    fi
    conf_part=`sed -n "/$attach_point/,\$"p $my_conf`
    sed -i "/$attach_point/,\$d" $my_conf
    
    all_mysql_conf="character-set-server = $mysql_char_set
lower_case_table_names = $mysql_lower_case
transaction_isolation = READ-COMMITTED

log-bin = mysql-bin
server-id=1
binlog_format = row
expire_logs_days = 7
max_binlog_size = 200M 
log-bin-trust-function-creators = 1

skip-external-locking
skip-name-resolve
skip-slave-start
skip-host-cache

wait_timeout = 86400
interactive_timeout = 86400
max_connections = 5000
max_allowed_packet = 100M

[client]
default-character-set = $mysql_char_set"
    
    #删除原有的配置参数
    mysql_conf_key=(${all_mysql_conf// = /=})
    for i in $mysql_conf_key
    do
      conf_key=`echo ${mysql_conf_key[$n]}|awk -F"=" '{print $1}'`
      sed -i "/$conf_key/d" $my_conf
    done
    
    # 设置MySQL密码策略
    if [ "$mysql_ins_ver" == "2" ];then
        echo -e "\n#validate_password_policy = 0\n#validate_password_length = 6\n" >>$my_conf
    elif [ "$mysql_ins_ver" == "3" ];then
        echo -e "\n#validate_password.policy = 0\n#validate_password.length = 6\n" >>$my_conf
    fi
    
    #添加新的配置
    cat >>$my_conf<<EOF
$all_mysql_conf
    
$conf_part
EOF
    
    echo -e "$Info ${purple}初始化MySQL${nocolor}"
    service mysqld restart>/dev/null 2>&1|| service mysql restart>/dev/null 2>&1
    sleep 1
    n=1
    ibdata_tm=`ls -l --time-style=full-iso|grep ibdata1|awk '{print $7}'`
    ibdata_tmc=0
    while [ "$ibdata_tm" != "$ibdata_tmc" ]
    do
      sleep 0.30
      ibdata_tm=`ls -l --time-style=full-iso|grep ibdata1|awk '{print $7}'`
      echo "等待MySQL初始化 ${n} ....."
      if [ $n -gt 40 ];then
        break
      fi
      sleep 1
      ibdata_tmc=`ls -l --time-style=full-iso|grep ibdata1|awk '{print $7}'`
      let n+=1
    done
    sleep 2
    echo -e "$Info ${purple}设置MySQL密码${nocolor}"

    if [[ $system_ver != [456] && "$mysql_ins_ver" == "2" ]];then
        systemctl stop mysqld >/dev/null 2>&1 || systemctl stop mysql >/dev/null 2>&1
        systemctl set-environment MYSQLD_OPTS="--skip-grant-tables"
        systemctl start mysqld >/dev/null 2>&1 || systemctl start mysql >/dev/null 2>&1
        systemctl unset-environment MYSQLD_OPTS
    else
        sed -i "/\[mysqld\]/a skip-grant-tables" $my_conf
        service mysqld restart>/dev/null 2>&1|| service mysql restart>/dev/null 2>&1
    fi
    sed -i 's/.*\(validate_password.*\)/\1/g' $my_conf
    sleep 1
    
    n=1
    mysql_status=`pidof mysqld`
    while [ -z "$mysql_status" ]
    do
      echo "等待MySQL启动"
      if [ $n -gt 25 ];then
        break
      fi
      sleep 1
      let n+=1
      mysql_status=`pidof mysqld`
    done
    
    mysql -uroot -e "update mysql.user set password_expired='N' where user='root';"
    if [ "$mysql_ins_ver" == "2" ];then
        mysql -uroot -e "update mysql.user set authentication_string=password('$mysql_passwd') where user='root';"
    elif [ "$mysql_ins_ver" == "3" ];then
        mysql -uroot -e "update mysql.user set authentication_string='' where user='root';"
    else
        mysql -uroot -e "UPDATE mysql.user SET Password = PASSWORD('$mysql_passwd') WHERE User = 'root';"
    fi
    
    sed -i "/skip-grant-tables/d" $my_conf
    
    echo -e "$Info ${purple}启动MySQL${nocolor}"
    service mysqld restart || service mysql restart
    mysql_status=`pidof mysqld`
    while [ -z "$mysql_status" ]
    do
      echo "等待MySQL启动"
      if [ $n -gt 25 ];then
        break
      fi
      sleep 1
      let n+=1
      mysql_status=`pidof mysqld`
    done
    echo -e "$Info ${purple}开启ROOT用户远程访问${nocolor}"
    if [ "$mysql_ins_ver" == "3" ];then
        mysql -uroot -e "ALTER user 'root'@'localhost' IDENTIFIED BY '$mysql_passwd';"
        mysql -uroot -p$mysql_passwd -e "flush privileges;"
        mysql -uroot -p$mysql_passwd -e "CREATE USER 'root'@'%' IDENTIFIED BY '$mysql_passwd';"
        mysql -uroot -p$mysql_passwd -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;"
        #mysql -uroot -p$mysql_passwd -e "update mysql.user set host='%' where user ='root';" >>$logs_file 2>&1
        
    else
        mysql -uroot -p$mysql_passwd -e "grant all privileges on *.* to root@'%' identified by '$mysql_passwd';"
    fi
    mysql -uroot -p$mysql_passwd -e "flush privileges;"
 
    echo ""
    echo ""
    mysql_ver=`rpm -qa|grep "mysql"|grep "server"|grep -Eo "[0-9]+\.[0-9]+\.[0-9]+"`
    mysql_is_run=`pidof mysqld`
    if [ -n "$mysql_is_run" ];then
        echo -e "$Info ${light_green}已经安装完成MySQL ${mysql_ver}${nocolor}"
        mysql -uroot -p$mysql_passwd -e "show databases;" >/dev/null 2>&1
        if [ "$?" == "0" ];then
          echo -ne "MySQL $mysql_ver安装成功，默认密码为$mysql_passwd
是否需要将密码保存到文件？
如果是，密码将已BASE64加密方式保存到文件/root/.MYDBPW
查看密码命令：cat /root/.MYDBPW |base64 -d|cut -b 7-
是[Yy,Enter], 否[Nn]: "
            read isYn
            if [[ $isYn != [Nn] ]];then
                echo "env.sh$mysql_passwd" |base64>/root/.MYDBPW
            fi
        else
          echo -e "$Warn MySQL安装成功，但是设置密码失败，
可能因为MySQL版本变化，导致修改密码失败，请参考官方文档重置密码！！"
        fi
    else
        echo -e "$Error MySQL安装失败"
    fi
    anykeyback
}


function install_mysql_online() {
    #判断yum是否在运行
    yum_pid=`ps aux|grep "/usr/bin/yum"|grep -v grep|awk '{print $2}'`
    if [ -n "$yum_pid" ];then
        for pid in $yum_pid
        do
         kill $pid >/dev/null 2>&1
         sleep 1
         kill -9 $pid >/dev/null 2>&1
        done
    fi
    echo -e "$Info ${purple}添加MySQL YUM源${nocolor}"
    if [[ $system_ver == [456] ]];then
        cat>/etc/yum.repos.d/mysql-community-qh.repo<<'EOF'
[mysql-connectors-community-qh]
name=MySQL Connectors Community
baseurl=https://mirrors.tuna.tsinghua.edu.cn/mysql/yum/mysql-connectors-community-el6-$basearch/
enabled=1
gpgcheck=1
gpgkey=https://repo.mysql.com/RPM-GPG-KEY-mysql

[mysql-tools-community-qh]
name=MySQL Tools Community
baseurl=https://mirrors.tuna.tsinghua.edu.cn/mysql/yum/mysql-tools-community-el6-$basearch/
enabled=1
gpgcheck=1
gpgkey=https://repo.mysql.com/RPM-GPG-KEY-mysql

[mysql-5.6-community-qh]
name=MySQL 5.6 Community Server
baseurl=https://mirrors.tuna.tsinghua.edu.cn/mysql/yum/mysql-5.6-community-el6-$basearch/
enabled=0
gpgcheck=1
gpgkey=https://repo.mysql.com/RPM-GPG-KEY-mysql

[mysql-5.7-community-qh]
name=MySQL 5.7 Community Server
baseurl=https://mirrors.tuna.tsinghua.edu.cn/mysql/yum/mysql-5.7-community-el6-$basearch/
enabled=1
gpgcheck=1
gpgkey=https://repo.mysql.com/RPM-GPG-KEY-mysql

[mysql-8.0-community-qh]
name=MySQL 8.0 Community Server
baseurl=https://mirrors.tuna.tsinghua.edu.cn/mysql/yum/mysql-8.0-community-el6-$basearch/
enabled=1
gpgcheck=1
gpgkey=https://repo.mysql.com/RPM-GPG-KEY-mysql
EOF
        rpm -ivh https://repo.mysql.com//mysql80-community-release-el6-3.noarch.rpm
    elif [ "$system_ver" == "7" ];then
        cat>/etc/yum.repos.d/mysql-community-qh.repo<<'EOF'
[mysql-connectors-community-qh]
name=MySQL Connectors Community
baseurl=https://mirrors.tuna.tsinghua.edu.cn/mysql/yum/mysql-connectors-community-el7-$basearch/
enabled=1
gpgcheck=1
gpgkey=https://repo.mysql.com/RPM-GPG-KEY-mysql

[mysql-tools-community-qh]
name=MySQL Tools Community
baseurl=https://mirrors.tuna.tsinghua.edu.cn/mysql/yum/mysql-tools-community-el7-$basearch/
enabled=1
gpgcheck=1
gpgkey=https://repo.mysql.com/RPM-GPG-KEY-mysql

[mysql-5.6-community-qh]
name=MySQL 5.6 Community Server
baseurl=https://mirrors.tuna.tsinghua.edu.cn/mysql/yum/mysql-5.6-community-el7-$basearch/
enabled=0
gpgcheck=1
gpgkey=https://repo.mysql.com/RPM-GPG-KEY-mysql

[mysql-5.7-community-qh]
name=MySQL 5.7 Community Server
baseurl=https://mirrors.tuna.tsinghua.edu.cn/mysql/yum/mysql-5.7-community-el7-$basearch/
enabled=1
gpgcheck=1
gpgkey=https://repo.mysql.com/RPM-GPG-KEY-mysql

[mysql-8.0-community-qh]
name=MySQL 8.0 Community Server
baseurl=https://mirrors.tuna.tsinghua.edu.cn/mysql/yum/mysql-8.0-community-el7-$basearch/
enabled=1
gpgcheck=1
gpgkey=https://repo.mysql.com/RPM-GPG-KEY-mysql
EOF
        rpm -ivh https://repo.mysql.com//mysql80-community-release-el7-3.noarch.rpm
    else
        cat>/etc/yum.repos.d/mysql-community-qh.repo<<'EOF'
[mysql-connectors-community-qh]
name=MySQL Connectors Community
baseurl=https://mirrors.tuna.tsinghua.edu.cn/mysql/yum/mysql-connectors-community-el8-$basearch/
enabled=1
gpgcheck=1
gpgkey=https://repo.mysql.com/RPM-GPG-KEY-mysql

[mysql-tools-community-qh]
name=MySQL Tools Community
baseurl=https://mirrors.tuna.tsinghua.edu.cn/mysql/yum/mysql-tools-community-el8-$basearch/
enabled=1
gpgcheck=1
gpgkey=https://repo.mysql.com/RPM-GPG-KEY-mysql

[mysql-8.0-community-qh]
name=MySQL 8.0 Community Server
baseurl=https://mirrors.tuna.tsinghua.edu.cn/mysql/yum/mysql-8.0-community-el8-$basearch/
enabled=1
gpgcheck=1
gpgkey=https://repo.mysql.com/RPM-GPG-KEY-mysql
EOF
        rpm -ivh https://repo.mysql.com//mysql80-community-release-el8-1.noarch.rpm
    fi
    
    echo -e "$Info ${purple}禁用不需要的mysql版本YUM源${nocolor}"
    yum clean all >/dev/null 2>&1
    sed -i 's/enabled=1/enabled=0/g' /etc/yum.repos.d/mysql-community.repo
    sed -i 's/enabled=1/enabled=0/g' /etc/yum.repos.d/mysql-community-qh.repo
    if [ "$mysql_ins_ver" == "1" ];then
        sed -i '/mysql-5.6-community/{:a;n;s/enabled=.*/enabled=1/g;/gpgcheck/!ba}' /etc/yum.repos.d/mysql-community.repo
        sed -i '/mysql-5.6-community/{:a;n;s/enabled=.*/enabled=1/g;/gpgcheck/!ba}' /etc/yum.repos.d/mysql-community-qh.repo
    elif [ "$mysql_ins_ver" == "2" ];then
        sed -i '/mysql-5.7-community/{:a;n;s/enabled=.*/enabled=1/g;/gpgcheck/!ba}' /etc/yum.repos.d/mysql-community.repo
        sed -i '/mysql-5.7-community/{:a;n;s/enabled=.*/enabled=1/g;/gpgcheck/!ba}' /etc/yum.repos.d/mysql-community-qh.repo
    else
        sed -i '/mysql-8.0-community/{:a;n;s/enabled=.*/enabled=1/g;/gpgcheck/!ba}' /etc/yum.repos.d/mysql-community.repo
        sed -i '/mysql-8.0-community/{:a;n;s/enabled=.*/enabled=1/g;/gpgcheck/!ba}' /etc/yum.repos.d/mysql-community-qh.repo
    fi    

    echo -e "$Info ${purple}开始安装，安装等待时间视网络情况而定${nocolor}"
    yum -y install libaio perl numactl perl-Data-Dumper perl-Module-Install mysql-community-server
    if [ "$?" != "0" ];then
        echo -e "$Error 安装失败，检查网络状态！"
        anykeyback
        return 1
    fi
}

function install_mysql_offline() {
    echo -e "$Info ${purple}使用离线安装MySQL${nocolor}"
    
    if [ "$mysql_ins_ver" == "1" ];then
        mysql_ver=`ls -r $workHome/packages/mysql/ 2>/dev/null|grep -i MySQL-5.6|head -n1|awk -F"-" '{print $2}'`
    elif [ "$mysql_ins_ver" == "2" ];then
        mysql_ver=`ls -r $workHome/packages/mysql/ 2>/dev/null|grep -i MySQL-5.7|head -n1|awk -F"-" '{print $2}'`
    elif [ "$mysql_ins_ver" == "3" ];then
        mysql_ver=`ls -r $workHome/packages/mysql/ 2>/dev/null|grep -i MySQL-8.0|head -n1|awk -F"-" '{print $2}'`
    fi
    
    yum -y install libaio perl numactl perl-Data-Dumper perl-Module-Install
    yum localinstall -y $workHome/packages/mysql/MySQL-${mysql_ver}/el${system_ver}/*.rpm
    if [ "$?" != "0" ];then
        echo -e "$Error 安装失败，检查网络状态！"
        anykeyback
        return 1
    fi
}